package cn.jdemo.juc.executors;

import java.util.concurrent.*;

/**
 * <a href="https://www.cnblogs.com/ants/p/11343657.html"></>
 * <a href="https://www.cnblogs.com/ants/p/11397863.html"></>
 */
public class Demo01 {
    public static void main(String[] args) throws InterruptedException {
        // test01();
        test02();
    }

    /**
     * 工作窃取算法:
     * 0
     * 1
     * ... ...
     */
    private static void test01() throws InterruptedException {
        ExecutorService executorService =
                Executors.newWorkStealingPool(2);// 并行度
        for (int i = 0; i < 5; i++) {
            final int taskIndex = i;
            executorService.execute(() -> {
                System.out.println(taskIndex);
                try {
                    Thread.sleep(Long.MAX_VALUE);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

        Thread.sleep(Long.MAX_VALUE);
    }

    /**
     * 输出内容(核心线程控制):
     * 1
     * 0
     * ... ...(无限等待)
     *
     * 为什么？--> 当线程数大于等于核心线程数，且任务队列未满时，将任务放入任务队列
     */
    private static void test02() {
        ThreadPoolExecutor executorService = new ThreadPoolExecutor(
                2, //corePoolSize
                100, //maximumPoolSize
                100, //keepAliveTime
                TimeUnit.SECONDS, //unit
                new LinkedBlockingDeque<>(100));//workQueue

        for (int i = 0; i < 5; i++) {
            final int taskIndex = i;
            executorService.execute(() -> {
                System.out.println(taskIndex);
                try {
                    Thread.sleep(Long.MAX_VALUE);// 无限等待
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
    }
}
